/*
Copyright  2018 Blockchain Technology and Application Joint Lab, Fintech Research Center of ISCAS.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
import React, {Component, PropTypes} from 'react';
import {createContainer} from 'meteor/react-meteor-data';
import {browserHistory} from 'react-router';
import {List, ListItem} from 'material-ui/List';
import {CopyrightCertificates} from '../api/copyright_certificates/copyright_certificates.js';
import {RegisterUser} from '../api/register_user/register_user';

import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import Avatar from 'material-ui/Avatar';
import {grey400, darkBlack, lightBlack} from 'material-ui/styles/colors';
import IconButton from 'material-ui/IconButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';

import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import Tab1List from './Tab1List.jsx';

import {GridTile, GridList} from 'material-ui/GridList';
import Camera from 'material-ui/svg-icons/image/camera';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ContentAdd from 'material-ui/svg-icons/content/add';

import InfiniteScroll from 'react-infinite-scroller';
import moment from 'moment';
import repchain from '../api/repchainUtil'

const styles = {
    footer: {
        position: 'fixed',
        bottom: 0,
        width: '100%',
    },
    root: {
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'space-around',
    },
    gridList: {
        width: '100%',
        height: '100%',
        overflowY: 'auto',
    },
}
const themes = ['picture_desc.name', 'picture_desc.author', 'owner_account_address',
    'block_timestamp', 'picture_desc.desc', 'picture_digital_identity'];

export class Tab1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            open: false,
            cerid: '',
            page: 0,
            hasMore: true,
            picItems: [],
            pageNum: 5,
            query: null,
            certificate: {},
            owner: {},
        }
    }
    componentWillUnmount(){
        this._isMounted = false;
    }

    setStateByCheck(po){
        if(this._isMounted){
            this.setState(po);
        }
    }
    //登录验证
    componentWillMount(){
        this._isMounted = true;
        if (this.props.myImages && Session.get('curUser') === 'none'){
            browserHistory.push('/login');
        }

    }

    componentDidUpdate(prevProps, prevState){
        if (this.props.myImages && Session.get('curUser') === 'none'){
            browserHistory.push('/login');
        }
    }

    componentDidMount(x, y, z) {
        this.setState({cw: window.innerWidth, ch: window.innerHeight});
    }

    handleClose() {
        this.setState({open: false});
    }


    loadmore(page){
        let pageNum = this.state.pageNum;
        let query = this.state.query;
        if(query != this.props.query){
            query = this.props.query;
            this.setState({query:this.props.query,hasMore:true, page:0,picItems:[]})
        }


        let offset = pageNum*(page-1);
        Meteor.subscribe('copyright_certificates',query, pageNum, offset);
        setTimeout(function(){
            offset = this.state.picItems.length;
            let res=CopyrightCertificates.find(query,{sort: { createdAt: -1 }, limit:pageNum, skip:offset }).fetch()
            if(res.length < pageNum){
                this.setStateByCheck({picItems:this.state.picItems.concat(res),hasMore:false})
                return;
            }else{
                this.setStateByCheck({picItems:this.state.picItems.concat(res), hasMore:true,})
            }
        }.bind(this),100)
    }

    handleQueryChange(props) {
        setTimeout(function(){
            this.setStateByCheck({hasMore:true,picItems:[],page:0,query:props.query})
        }.bind(this),100);
    }


    handleTouchTap(cerid) {
        Meteor.subscribe('copyright_certificate',{certificate_number: cerid});
        let certificate_info = CopyrightCertificates.findOne({certificate_number: cerid});
        Meteor.subscribe('registerUser', {account_address:certificate_info.owner_account_address});
        setTimeout(function () {
            let owner = RegisterUser.findOne({account_address:certificate_info.owner_account_address})
            this.setState({certificate: certificate_info, owner: owner})
        }.bind(this),100)
    }

    renderItems() {
        let result = [];
        this.state.picItems.map((item, index) => {
                if (!item.status || item.block_timestamp == -1) {
                    repchain.getTransaction(item.certificate_number, (err, result) => {
                        if (err) {
                        }
                        else {
                            Meteor.call('certificate.update', result,(err,result)=>{
                                console.log(err||result)
                            });
                        }
                    });
                }
                let pic_desc = item.picture_desc;
                let pic_url = pic_desc.picture_url.search("^http")>=0 ? pic_desc.picture_url : 'http://'+window.location.host+ pic_desc.picture_url;
                result.push(
                    <GridTile
                        key={item.certificate_number}
                        // Note: setState is not a synch function
                        onTouchTap={() => {
                            this.handleTouchTap(item.certificate_number)
                            this.setState({open: true})
                        }}
                        actionIcon={<IconButton><Camera color={item.status ? "green" : "red"}/></IconButton>}
                        actionPosition={'left'}
                        title={pic_desc.name}
                        style={{height: 200}}
                    >
                        <img src={pic_url} alt=''/>
                    </GridTile>
                );
            }
        );
        return result;
    }

    render() {
        return (
            <div style={styles.root}>
                {this.props.query == this.state.query ? null : this.handleQueryChange(this.props)}
                <GridList cellHeight={'auto'} style={styles.gridList} cols={1} padding={4}>
                    <InfiniteScroll
                        pageStart={this.state.page}
                        loadMore={this.loadmore.bind(this)}
                        hasMore={this.state.hasMore}
                        loader={<div className='loader'>Loading...</div>}
                    >
                        {this.renderItems()}
                    </InfiniteScroll>
                </GridList>
                <Drawer width={this.state.open ? this.state.cw : 0}
                        containerStyle={{position: 'fixed', top: 0, overflowY: 'hidden'}}
                        openSecondary={true} open={this.state.open}>
                    <Tab1List
                        certificate={this.state.certificate}
                        owner={this.state.owner||{}}
                        myImages={this.props.myImages}
                        handleClose={this.handleClose.bind(this)}
                    />
                </Drawer>
                {this.props.myImages ?
                    <div id='addImage'>
                        <FloatingActionButton style={{position: 'fixed', bottom: 65, right: 5,}}
                                              backgroundColor='rgba(77, 208, 225, 0.65)' onClick={(event) => {
                            if (Session.get('curUser').account_address == 'none') {
                                console.log("请联系管理员，证书还未确认！")
                            } else {
                                browserHistory.push('/register');
                            }
                        }}>
                            <ContentAdd/>
                        </FloatingActionButton>
                    </div>
                    : ''
                }
            </div>
        );
    }
}

Tab1.propTypes = {
    query: PropTypes.object.isRequired
};
Tab1.defaultProps = {
    myImages: false
}

export default createContainer((props) => {
    let query = {};
    if(props.search_text){
        let rtx = ".*" + props.search_text + ".*";
        let theme_index = props.search_theme;
        query[themes[theme_index]] = {$regex: rtx};
    }
    if(props.myImages){
        let query2 = {owner_account_address: Session.get('curUser').account_address};
        let query3 = {$and: [query, query2]}
        query = query3;
    }
    console.log(query)

    return {
        query: query
    }
}, Tab1);
